package top.frsf.rpc.channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import top.frsf.rpc.code.decode.RpcMessageDecoder;
import top.frsf.rpc.code.encode.RpcMessageEncoder;
import top.frsf.rpc.handler.RpcServiceInvokeHandler;

import static top.frsf.rpc.constants.RpcConstants.*;

/**
 * @author He Kuntao
 * @since 2025/7/8 15:05
 */
@RequiredArgsConstructor
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final ApplicationContext context;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(
                // 1.Netty自带协议解码器，解决粘包、半包问题
                new LengthFieldBasedFrameDecoder(
                        MAX_FRAME_LENGTH,
                        LENGTH_FIELD_OFFSET,
                        LENGTH_FIELD_LENGTH,
                        NUM_SKIP_BODY_LENGTH,
                        FINISH_SKIP_LENGTH
                ),
                // 2.自定义协议解码器
                new RpcMessageDecoder(),
                // 3.自定义协议编码器
                new RpcMessageEncoder(),
                // 4.RPC 服务调用处理器
                new RpcServiceInvokeHandler(context)
        );
    }
}
